package logger

import (
	"fmt"
	"os"
	"path/filepath"
)

// Config holds logging configuration
type Config struct {
	// Basic configuration
	Level  string `mapstructure:"level"`  // debug, info, warn, error
	Format string `mapstructure:"format"` // json, console

	// Output configuration
	Path           string `mapstructure:"path"`            // Log file path
	ConsoleEnabled bool   `mapstructure:"console_enabled"` // Enable console output

	// Debug options
	EnableCaller     bool `mapstructure:"enable_caller"`     // Enable caller information
	EnableStacktrace bool `mapstructure:"enable_stacktrace"` // Enable stacktrace

	// File rotation configuration (lumberjack)
	MaxSize    int `mapstructure:"max_size"`    // Single log file max size before rotation (MB)
	MaxAge     int `mapstructure:"max_age"`     // Time to live (days)
	MaxBackups int `mapstructure:"max_backups"` // Max log file count
}

// DefaultConfig returns default configuration
func DefaultConfig() *Config {
	return &Config{
		Level:            "info",
		Format:           "console",
		ConsoleEnabled:   true,
		EnableCaller:     true,
		EnableStacktrace: false,
	}
}

// Validate validates configuration
func (c *Config) Validate() error {
	// Validate log level
	validLevels := map[string]bool{
		"debug": true, "info": true, "warn": true, "error": true,
	}
	if !validLevels[c.Level] {
		return fmt.Errorf("invalid log level: %s", c.Level)
	}

	// Validate format
	validFormats := map[string]bool{"json": true, "console": true}
	if !validFormats[c.Format] {
		return fmt.Errorf("invalid log format: %s", c.Format)
	}

	// Validate path
	if c.Path != "" {
		dir := filepath.Dir(c.Path)
		if err := os.MkdirAll(dir, 0755); err != nil {
			return fmt.Errorf("cannot create log directory: %v", err)
		}
	}

	return nil
}
